import { WeaDialog, WeaNewScroll, WeaRadioGroup, WeaProgress, WeaTools, WeaInputSearch, WeaTable, WeaLocaleProvider, WeaRightMenu } from 'ecCom';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Tooltip, Row, Col, Progress, Button, Spin, Modal } from 'antd';
import Collapse from './collapse.js';
import { WeaTableNew } from 'comsMobx';
import VoteUrgent from './VoteUrgent';
import Suggestions from '../../components/result/Suggestions';
import * as Api from '../../apis/votingList';

const WeaTableMobx = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
const Base64 = WeaTools.Base64;

@inject('votingVotingList')
@observer
export default class VotingDialog extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      urgentVisible: false,
      suggestionVisible: false,
    };
  }

  componentDidMount() {
    let { getRadioGroup } = this.props.votingVotingList; // 获取统计范围列表
    getRadioGroup();
  }

  componentWillReceiveProps(nextProps) {

  }

  componentDidUpdate(prevProps, prevState) {

  }

  close = () => {
    this.props.close && this.props.close();
  }
  WeaRadioGroupChange = (params) => {
    let { getDialogAllDatas } = this.props.votingVotingList;
    getDialogAllDatas(undefined, params);// 因为只走2个接口
  }

  onSearch = (param) => {
    let { getPersonList } = this.props.votingVotingList;
    getPersonList('', undefined, { username: param });
  }

  getTableList = () => {
    let { getPersonList, status } = this.props.votingVotingList;
    let { votingDialogList } = toJS(status);
    let arr = votingDialogList ? votingDialogList.map((record, index) => {
      let contain = this.getContainTable(record.otherView, record);
      let hasLabel = this.getHasLabel(contain, record);
      return hasLabel;
    }) : [];

    return arr;
  }
  getHasLabel = (contain, record) => {
    const { setPersonListDialog } = this.props.votingVotingList;
    let prefixCls = 'voting-dialog';
    return (
      <div style={{ marginBottom: '10px' }}>
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@zbgi4t`} style={{ height: '38px', lineHeight: '38px', backgroundColor: '#f8fcff' }}>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@iscmj7`} span="18" style={{ paddingLeft: '25px' }}>
            <span className={`${prefixCls}-table-title`} title={record.label}>{record.label}</span>
            <span className={`${prefixCls}-table-title-ext`}>{record.labelExt}</span>
            {/* {`${record.label}${record.labelExt}`} */}
          </Col>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@eevkvk`} span="6" style={{ paddingRight: '25px', textAlign: 'right' }}>
            <a onClick={() => { // 查看列表弹出框
              setPersonListDialog(true, 'questionList', record.questionid);
            }}
            >
              {`${record.percent}`}
            </a>
          </Col>
        </Row>
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@xpy12f`}>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@00a1bc`}>
            <div className="votingDialog-noTableHeader">
              {contain}
            </div>
          </Col>
        </Row>
      </div>
    );
  }
  getContainTable = (type, record) => { // 0-单选不含其他，1-单选含其他，2-组合，3-填空
    const { setPersonListDialog, status } = this.props.votingVotingList;
    if (type == 0) {
      let columns = this.getContainTableColumns(record.columns, type, record);
      return (<WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@civs7l`} columns={columns} dataSource={record.dataSource} pagination={false} />);
    } else if (type == 1) {
      let columns = this.getContainTableColumns(record.columns, type, record);

      return [
        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@r2k5gm@${record.questionid}`} columns={columns} dataSource={record.dataSource} pagination={false} />,
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@7thy0d@${record.questionid}`}>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@elejb6@${record.questionid}`} style={{ lineHeight: '38px', height: '38px' }}>
            <div className="addHover">
              <span className="icon-coms-List" style={{ color: '#4d7ad8', paddingLeft: '28px' }} />
              <a style={{ paddingLeft: '8px' }}
                onClick={() => { // 查看列表弹出框
                  setPersonListDialog(true, 'other', record.questionid);
                }}
              >
                {getLabel(25740, '其他')}
              </a>
            </div>

          </Col>
        </Row>,
      ];
    } else if (type == 2) {
      let columns = this.getContainTableColumns(record.columns, type, record);
      return (
        <div className="addHeader">
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@bi00r9`} columns={columns} dataSource={record.dataSource} pagination={false} />
        </div>
      );
    } else if (type == 3) {
      return (
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@1mu4g9`}>
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@6f15ll`} style={{ lineHeight: '38px', height: '38px' }}>
            <div className="addHover">
              <span className="icon-coms-List" style={{ color: '#4d7ad8', paddingLeft: '28px' }} />
              <a style={{ paddingLeft: '8px' }}
                onClick={() => { // 查看列表弹出框
                  // setPersonListDialog(true, 'agree', record.questionid)
                  this.setState({ suggestionVisible: true }, () => {
                    this.suggestionRef && this.suggestionRef.wrappedInstance.getDatas({
                      ...status.WeaRadioGroupParams,
                      questionid: record.questionid,
                      votingid: status.votingDialogId,
                    });
                  });
                }}
              >
                {getLabel(385156, '查看列表')}
              </a>
            </div>
          </Col>
        </Row>
      );
    }
  }
  getContainTableColumns = (columns, type, record) => {
    const { setPersonListDialog } = this.props.votingVotingList;
    let parentRecord = { ...record };
    let newColumns = { ...columns };
    newColumns = columns.map((element, index) => {
      if (element.dataReader == 'value') {
        return element;
      }
        element.render = (text, record, index) => {
          let percent = record.qnums == 0 ? 0 : (text / record.qnums).toFixed(4);
          percent = Math.round(percent * 10000) / 100;

          let TooltipTitle = record.qnums == 0 ? '0（0%）' : `${text}（${percent}%）`;

          let optionid = record.optionid;

          if (optionid.indexOf('_') > -1) {
            optionid = `${record.key}_${element.key.split('_')[1]}`;
          }

          if (type == 2) {
            return (
              <div>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@u2ta1o@${record.questionid}`}>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@vz41w7`} >
                    <Progress ecId={`${this && this.props && this.props.ecId || ''}_Progress@67b08e`} percent={percent} showInfo={false} />
                  </Col>
                </Row>
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@nt6y9h@${record.questionid}`}>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4o6ykx`} >
                    <a
                      style={{ paddingLeft: '8px' }}
                      onClick={// 显示投票详情
                        () => {
                          setPersonListDialog(true, 'optionList', parentRecord.questionid, optionid);
                        }
                      }
                    ><span style={{ fontSize: '12px' }}> {TooltipTitle}</span></a>
                  </Col>
                </Row>
              </div>
            );
          }

          return (
            <div>
              <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@tbu00e@${record.questionid}`}>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@sfgv2u@${record.questionid}`} span="18">
                  <Progress ecId={`${this && this.props && this.props.ecId || ''}_Progress@ao6cmi@${record.questionid}`} percent={percent} showInfo={false} />
                </Col>
                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4lah4x@${record.questionid}`} span="6">
                  <a
                    style={{ paddingLeft: '8px' }}
                    onClick={// 显示投票详情
                      () => {
                        setPersonListDialog(true, 'optionList', parentRecord.questionid, optionid);
                      }
                    }
                  ><span style={{ fontSize: '12px' }}> {TooltipTitle}</span></a>
                </Col>
              </Row>

            </div>
          );
        };
        return element;
    });
    return newColumns;
  }
  getButton = () => {
    const { votingVotingList: { isurgent, status } } = this.props;
    return [
      isurgent * 1 === 1 && <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8jqxfr@urgentBtn`} type="primary" onClick={this.urgent}>{getLabel('500432', '催办')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7odnq6@printPreviewBtn`} type="primary" onClick={() => this.printPreview(status.votingDialogId)}>{getLabel('20757', '打印预览')}</Button>,
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@eaojm1@exportExcelBtn`}
        type="primary"
        disabled={false}
        onClick={() => {
        this.exportExcel();
      }}
      >{getLabel('518717', '导出数据明细')}</Button>,
    ];
  }

  // 打印预览
  printPreview = (id) => {
    const { votingVotingList: { status }, votingDialogTitle } = this.props;
    let title = Base64.encode(votingDialogTitle);
    let radioPramas = toJS(status).WeaRadioGroupParams;
    let params = '';
    radioPramas && Object.keys(radioPramas).forEach((item) => {
      params += `&${item}=${radioPramas[item]}`;
    });
    localStorage.setItem('surveyTitle', title);
    openFullWindowHaveBar(`/spa/smallApp/static/index.html#/main/voting/preview?id=${id}${params}`);
  }

  // 催办
  urgent = () => {
    const { status } = this.props.votingVotingList;
    const { votingDialogId } = toJS(status);

    Api.urgentNum({ votingid: votingDialogId }).then((res) => {
        if (res.num * 1) {
            this.setState({ urgentVisible: true });
            if (this.urgentRef) {
              this.urgentRef.getDatas();
            }
        } else {
            Modal.warning({
                title: getLabel('516746', '调查已全部填写，无须进行催办'),
                okText: getLabel('826', '确定'),
            });
        }
    });
  }

  exportExcel = () => {
    const { status } = this.props.votingVotingList;
    const { votingDialogId, WeaRadioGroupParams } = toJS(status);
    let arr = [],
groupParams = '';
    for (let key in WeaRadioGroupParams) {
      arr.push(`${key}=${WeaRadioGroupParams[key].replace(/\"/g, '')}`);
    }
    groupParams = arr.join('&');
    window.open(`/voting/ObtainExcelData.jsp?votingid=${votingDialogId}&${groupParams}`);
  }
  getColumns = (e) => {
    let { status, form, setCustomDialog } = this.props.votingVotingList;

    let newColumns = '';
    newColumns = e.map((column) => {
      let newColumn = { ...column };
      if (newColumn.dataIndex == 'opeator') {
        newColumn.render = (text, record, index) => { // 前端元素转义
          let valueSpan = record[`${newColumn.dataIndex}span`] !== undefined ? record[`${newColumn.dataIndex}span`] : record[newColumn.dataIndex];
          return (
            <div className="wea-votinglist-canClick wea-url-name"
              style={{ cursor: 'pointer' }}
              dangerouslySetInnerHTML={{ __html: valueSpan }}
              onClick={() => {
                setCustomDialog(true, record.opeatorKeyspan, 'details');
              }}
            />
          );
        };
        return newColumn;
      }
        return newColumn;
    });
    return newColumns;
  }


  render() {
    let { visible = false, votingDialogList, votingDialogTitle } = this.props;
    let { status, setPersonListDialog, comsWeaTableStore, setCustomDialog, getData } = this.props.votingVotingList;
    let {
      personListDialog, personListDialogType, allSessionkey,
      totalSize, doSize, unDoSize, dialogCondition, votingDialogSpin,
      customDialog, customDialogType, opeatorKeyspan, votingDialogId, notShowExport,

    } = toJS(status);

    let percent = doSize * 100 / totalSize;
    percent = Math.floor(percent * 100) / 100;
    let TooltipTitle = totalSize == 0 ? '0' : `${getLabel(33849, '已参与')}：${doSize}（${percent}%）`;
    let customDialogIframeSrc = customDialogType == 'details' ? `/voting/surveydesign/pages/mysurveyinput.jsp?votingid=${votingDialogId}&sourceid=${opeatorKeyspan}`
      : '';

    const rightMenu = {
      datas: () => [
          {
            key: 'BTN_EXPORT',
            content: getLabel('518717', '导出数据明细'),
            icon: <i className="icon-coms-leading-in" />,
            onClick: this.exportExcel,
          },
        ],
    },
collectParams = {
      datas: () => ({
          favname: `${getLabel(20042, '调查结果')}：${votingDialogTitle}`,
          favouritetype: 2,
          objid: 0,
          importantlevel: 1,
          link: 'wui/index.html#/main/voting/votingList',
        }),
    };

    const personBtns = notShowExport ? [] : [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nd70sg@exportExcelBtn`} type="primary" onClick={this.exportExcel}>{getLabel('518717', '导出数据明细')}</Button>,
    ];
    return (
      <div>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@8o4889`}
          visible={visible}
          title={`${getLabel(20042, '调查结果')}：${votingDialogTitle}`}
          className="votingDialog"
          icon="icon-coms-investigate"
          buttons={this.getButton()}
          moreBtn={{
            datas: rightMenu.datas(),
            collectParams: collectParams.datas(),
          }}
          iconBgcolor="#6D3CF7"
          style={{ width: '890px', height: '540px' }}
          onCancel={this.close}
        >
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@68etz1`} datas={rightMenu.datas()} collectParams={collectParams.datas()}>
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@g7jiuv`} height="100%">
              <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@oepe7u`} spinning={votingDialogSpin}>
                <Collapse ecId={`${this && this.props && this.props.ecId || ''}_Collapse@rmzsfj`}
                  title={getLabel(81884, '统计范围')}
                  showGroup={true}
                >
                  <WeaRadioGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaRadioGroup@rhzmtv`}
                    config={dialogCondition}
                    beforeInit={(a, b, c) => {
                      c(b);
                    }
                    }
                    onChange={(params) => {
                      this.WeaRadioGroupChange(params);
                    }}
                  />
                </Collapse>
                <Collapse ecId={`${this && this.props && this.props.ecId || ''}_Collapse@bwo29f`}
                  title={getLabel(83274, '参与情况')}
                  showGroup={true}
                  childrenStyle={{ textAlign: 'center' }}
                >
                  <div style={{ display: 'inline-block', width: '260px' }}>
                    <div>
                      <Tooltip ecId={`${this && this.props && this.props.ecId || ''}_Tooltip@pxi9yz`} placement="right" title={TooltipTitle}>
                        <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@kx4vkm`}
                          type="circle"
                          percent={doSize * 100 / totalSize}
                          strokeColor="#2db7f5"
                          format={percent => (
                              <div>
                                <div style={{ fontSize: '28px' }}>
                                  {totalSize}

                                  {/* <a onClick={() => {
                                            // this.getPersonList()
                                            }}>
                                            </a> */}
                                </div>
                                <div style={{ fontSize: '12px' }}>
                                  {getLabel(385157, '应参与')}
                                </div>
                              </div>
                            )}
                        />
                      </Tooltip>

                    </div>
                    <div>
                      <div style={{ display: 'inline-block', float: 'left' }}>
                        <div>
                          <a onClick={() => {
                            setPersonListDialog(true, 'participate');
                          }}
                            style={{ fontSize: '24px' }}
                          >{doSize}</a>
                        </div>
                        <div>
                          <span style={{
                            display: 'inline-block',
                            width: '6px',
                            height: '6px',
                            borderRadius: '3px',
                            marginRight: '8px',
                            backgroundColor: '#2db7f5',
                          }}
                          /><span>{getLabel(33849, '已参与')}</span>
                        </div>
                      </div>
                      <div style={{ display: 'inline-block', float: 'right' }}>

                        <div>
                          <a onClick={() => {
                            setPersonListDialog(true, 'notInvolved');
                          }}
                            style={{ fontSize: '24px', color: '#999999' }}
                          >{unDoSize}</a>

                        </div>
                        <div>
                          <span style={{
                            display: 'inline-block',
                            width: '6px',
                            height: '6px',
                            borderRadius: '3px',
                            marginRight: '8px',
                            backgroundColor: '#999999',
                          }}
                          /><span>{getLabel(33850, '未参与')}</span>

                        </div>
                      </div>
                    </div>
                  </div>
                </Collapse>
                <Collapse ecId={`${this && this.props && this.props.ecId || ''}_Collapse@p11dzv`}
                  title={getLabel(25177, '统计报表')}
                  showGroup={true}
                >
                  {
                    this.getTableList()
                  }
                </Collapse>

              </Spin>
            </WeaNewScroll>
          </WeaRightMenu>
        </WeaDialog >
        {
          personListDialog && <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@hp2hho`}
            hasScroll
            visible={personListDialog}
            title={`${personListDialogType}`}
            className="votingPersonList"
            icon="icon-coms-investigate"
            iconBgcolor="#6D3CF7"
            // style={{width: '890px', height: '600px'}}
            style={{ width: '890px', height: '540px' }}
            buttons={personBtns}
            moreBtn={{
              // datas: notShowExport ? [] : rightMenu.datas(),
              collectParams: {
                ...collectParams.datas(),
                favname: personListDialogType,
              },
            }}
            onCancel={() => {
              setPersonListDialog(false, '');
            }}
          >
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@qv51zi`}
              datas={notShowExport ? [] : rightMenu.datas()}
              collectParams={{
                ...collectParams.datas(),
                favname: personListDialogType,
              }}
            >
              <div style={{ padding: '10px 30px 10px 0', textAlign: 'right', borderBottom: '1px solid #eaeaea' }}>
                <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@x4x85t`} onSearch={this.onSearch} />

              </div>
              {comsWeaTableStore.dialog && personListDialog && <WeaTableMobx ecId={`${this && this.props && this.props.ecId || ''}_WeaTableMobx@pybnpn`}
                hasOrder={true}
                needScroll={false}
                sessionkey={allSessionkey.dialog}
                comsWeaTableStore={comsWeaTableStore.dialog}
                getColumns={this.getColumns}

              />}
            </WeaRightMenu>
          </WeaDialog>
        }

        {
          customDialog && <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@kerxsl`}
            visible={customDialog}
            title={getLabel(385155, '详细数据')}
            className="votingcustomDialog"
            icon="icon-coms-investigate"
            iconBgcolor="#6D3CF7"
            // style={{width: '890px', height: '600px'}}
            style={{ width: '890px', height: '540px' }}
            buttons={[]}
            moreBtn={{
              collectParams: {
                ...collectParams.datas(),
                favname: getLabel(385155, '详细数据'),
              },
            }}
            onCancel={() => {
              setCustomDialog(false);
            }}
          >

            <iframe
              width="890px"
              // height="600px"
              height="540px"
              src={customDialogIframeSrc}
            />

          </WeaDialog>
        }
        <VoteUrgent ecId={`${this && this.props && this.props.ecId || ''}_VoteUrgent@towj8q`}
          ref={ref => this.urgentRef = ref}
          visible={this.state.urgentVisible}
          onCancel={() => this.setState({ urgentVisible: false })}
          voteName={votingDialogTitle}
          voteid={votingDialogId}
          openUnInvitedList={() => setPersonListDialog(true, 'urgent', '', '', true)}
        />
        <Suggestions ecId={`${this && this.props && this.props.ecId || ''}_Suggestions@bb3naa`}
          ref={ref => this.suggestionRef = ref}
          visible={this.state.suggestionVisible}
          onCancel={() => this.setState({ suggestionVisible: false })}
          voteName={votingDialogTitle}
          voteid={votingDialogId}
          exportExcel={this.exportExcel}
          notShowExport={notShowExport}
        />
      </div>
    );
  }
}
